package yams.resource.impl;

import com.google.common.collect.Lists;
import javafx.util.Callback;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import yams.domain.ContractEntity;
import yams.resource.IContractResource;
import yams.resource.JsonCommonResource;
import yams.response.JsonResponse;
import yams.response.Response;
import yams.service.IContractService;
import yams.utils.BreezeeUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 合同管理对外服务
 * Created by Silence on 2016/11/1.
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/contract")
public class DefaultContractResource extends JsonCommonResource implements IContractResource {

    @Resource
    private IContractService contractService;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @Override
    public JsonResponse<ContractEntity> page(@RequestBody ContractEntity contractEntity) {
        //日期查找bug---格式化日期类型(合同日期在搜索范围之内的)
        try {
          /*  if (contractEntity.getProperties().get("_startDate") != null) {
                contractEntity.getProperties().put("startDate_gt", BreezeeUtils.DATE_FORMAT_SHORT.parse(contractEntity.getProperties().get("_startDate").toString()));
            }
            if (contractEntity.getProperties().get("_endDate") != null) {
                contractEntity.getProperties().put("endDate_le", BreezeeUtils.DATE_FORMAT_SHORT.parse(contractEntity.getProperties().get("_endDate").toString()));
            }*/
            if (contractEntity.getProperties().get("startDate_gt") != null && !StringUtils.isEmpty(contractEntity.getProperties().get("startDate_gt"))) {
                contractEntity.getProperties().put("startDate_gt", BreezeeUtils.DATE_FORMAT_LONG.parse(contractEntity.getProperties().get("startDate_gt").toString() + " 00:00:00"));
            }
            if (contractEntity.getProperties().get("startDate_le") != null && !StringUtils.isEmpty(contractEntity.getProperties().get("startDate_le"))) {
                contractEntity.getProperties().put("startDate_le", BreezeeUtils.DATE_FORMAT_LONG.parse(contractEntity.getProperties().get("startDate_le").toString()+" 23:59:59"));
            }
            if (contractEntity.getProperties().get("endDate_gt") != null && !StringUtils.isEmpty(contractEntity.getProperties().get("endDate_gt"))) {

                contractEntity.getProperties().put("endDate_gt", BreezeeUtils.DATE_FORMAT_LONG.parse(contractEntity.getProperties().get("endDate_gt").toString()+ " 00:00:00"));
            }
            if (contractEntity.getProperties().get("endDate_le") != null && !StringUtils.isEmpty(contractEntity.getProperties().get("endDate_le"))) {

                contractEntity.getProperties().put("endDate_le", BreezeeUtils.DATE_FORMAT_LONG.parse(contractEntity.getProperties().get("endDate_le").toString()+ " 23:59:59"));
            }



        } catch (ParseException e) {
            e.printStackTrace();
        }

        return _pageAll(contractService, contractEntity);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @Override
    public JsonResponse<ContractEntity> findById(@PathVariable String id) {
        return _findOne(contractService, id, 0);
    }

    @RequestMapping(value = "/code/{code}", method = RequestMethod.GET)
    @Override
    public JsonResponse<ContractEntity> findByCode(@PathVariable String code) {
        return _findOne(contractService, code, 1);
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @Override
    public JsonResponse<ContractEntity> save(@RequestBody ContractEntity contractEntity) {
        return _saveInfo(contractService,contractEntity,(Callback<ContractEntity, Object>) param -> {
            if (StringUtils.isEmpty(param.getId())){
                String nextPayDate = "";
                Date startDate = param.getStartDate();
                Integer cycle = param.getPayCycle();
                switch (cycle){
                    case 1:
                        nextPayDate = LocalDateTime.ofInstant(startDate.toInstant(), ZoneId.systemDefault())
                                .plusMonths(1).format(DateTimeFormatter.ISO_LOCAL_DATE);
                        break;
                    case 2:
                        nextPayDate = LocalDateTime.ofInstant(startDate.toInstant(), ZoneId.systemDefault())
                                .plusMonths(2).format(DateTimeFormatter.ISO_LOCAL_DATE);
                        break;
                    case 3:
                        nextPayDate = LocalDateTime.ofInstant(startDate.toInstant(), ZoneId.systemDefault())
                                .plusMonths(3).format(DateTimeFormatter.ISO_LOCAL_DATE);
                        break;
                    case 6:
                        nextPayDate = LocalDateTime.ofInstant(startDate.toInstant(), ZoneId.systemDefault())
                                .plusMonths(6).format(DateTimeFormatter.ISO_LOCAL_DATE);
                        break;
                    case 12:
                        nextPayDate = LocalDateTime.ofInstant(startDate.toInstant(), ZoneId.systemDefault())
                                .plusMonths(12).format(DateTimeFormatter.ISO_LOCAL_DATE);
                        break;
                    default:
                        break;
                }
                param.setNextPayDate(nextPayDate);
            }
            return null;
        });
    }

    /**
     * 生成合同，第一次账单(包括租金和押金)
     * @param contractEntity
     * @return
     */
    @RequestMapping(value = "/initBill", method = RequestMethod.PUT)
    public JsonResponse<ContractEntity> initBill(@RequestBody ContractEntity contractEntity) {

        List<String> paramList = Lists.newArrayList();
        paramList.add(contractEntity.getId());
        contractService.generateRentBill(paramList);
        return JsonResponse.OK();

    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @Override
    public JsonResponse<ContractEntity> delete(@PathVariable String id) {
        return _delete(contractService, id);
    }

    @Override
    public void initService() {
    }

    //自动创建合同编码
    @RequestMapping(value = "/autoCode", method = RequestMethod.POST)
    @Override
    public Response<ContractEntity> autoCode(ContractEntity contractEntity) {
        ContractEntity A = contractService.gaenerateContractCode(contractEntity);
        return JsonResponse.buildSingle(A);
    }

    //修改合同状态
    @RequestMapping(value = "/saveStatus", method = RequestMethod.PUT)
    public JsonResponse<ContractEntity> saveStatus(@RequestBody ContractEntity houseEntity) {
        ContractEntity result  = contractService.findById(houseEntity.getProperties().get("id").toString());
        result.setStatus(Integer.valueOf(houseEntity.getProperties().get("status").toString()));
        return _saveInfo(contractService, result);
    }
}
